package android.framework.rpc.convertor;

public class PrimitiveHandler {//TODO: extend for all primitive type
	private static final String NULL = "%%%NULL%%%";
	public static Object convert(MemberInfo memberInfo){
		if(memberInfo.isClass()){
			throw new IllegalArgumentException("can't convert non primitive type");
		}
		if(memberInfo.getValue().equals(NULL)){
			return null;
		}
		
		if(memberInfo.getType().equals(String.class)){
			return new String(memberInfo.getValue());
		}
		else if(memberInfo.getType().equals(Integer.class) || memberInfo.getType().equals(int.class)){
			return Integer.parseInt(memberInfo.getValue());
		}
		else if(memberInfo.getType().equals(Boolean.class) || memberInfo.getType().equals(boolean.class)){
			return Boolean.parseBoolean(memberInfo.getValue());
		}
		else{
			throw new IllegalArgumentException(String.format("can't convert primitive type: type %s is unknown", memberInfo.getType().getName()));
		}
	}
	
	public static String primitiveToString(Object obj){ 
		if(obj == null){
			return new String(NULL);
		}
		
		Class<?> cls = obj.getClass();
		if(!isPrimitive(cls)){
			throw new IllegalArgumentException("can't convert non primitive type");
		}
		
		if(cls.equals(String.class)){
			return obj.toString();
		}
		else if(cls.equals(Integer.class) || cls.equals(int.class)){
			return Integer.toString((Integer)obj);
		}
		else if(cls.equals(Boolean.class) || cls.equals(boolean.class)){
			return Boolean.toString((Boolean)obj);
		}
		else{
			throw new IllegalArgumentException(String.format("can't convert object to primitive type: type %s is unknown", cls.getName()));
		}
	}
	
	public static boolean isPrimitive(Class<?> cls){
		if(cls.equals(String.class)){
			return true;
		}
		else if(cls.equals(Integer.class) || cls.equals(int.class)){
			return true;
		}
		else if(cls.equals(Boolean.class) || cls.equals(boolean.class)){
			return true;
		}
		else{
			return false;
		}
	}
}
